package com.example.tb;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.mingle.widget.LoadingView;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.UnknownHostException;

/**
 * Created by 汪贵春 on 2016/5/24.
 */
public class ContentActivity extends AppCompatActivity{

    private String data = null;
    private TextView tvRange;
    private TextView tvPhonetics;
    private TextView tvTranslation;
    private LoadingView tvLoading;

    private static final int TIMEOUT     = 0;       //存放超时信息
    private static final int RANGE       = 1;       //存放单词出现范围
    private static final int PHONETICS   = 2;       //存放音标
    private static final int TRANSLATION = 3;       //存放翻译
    private static final boolean SAVE_HTML= false;  //是否保存html
    private static final int TIME_LIMIT  = 3000;    //设置超时时间

    //新建一个handler
    private Handler handler = new Handler(){

        public void handleMessage(Message msg){

            tvLoading.setVisibility(View.INVISIBLE);
            switch (msg.what){
                case TIMEOUT:
                    tvRange.setText("sorry，连接失败，请查看网络是否通畅。。。");
                    break;
                case RANGE:
                    if(msg.obj.toString().equals("")){
                        tvRange.setHeight(0);
                    }else{
                        tvRange.setText(msg.obj.toString());
                    }
                    break;
                case PHONETICS:
                    if(msg.obj.toString().equals("")){
                        tvPhonetics.setHeight(0);
                    }else{
                        tvPhonetics.setText(msg.obj.toString());
                    }
                    break;
                case TRANSLATION:
                    tvTranslation.setText(msg.obj.toString());
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //获取输入框中的值
        data = getIntent().getStringExtra("word");
        //设置标题
        if(data.equals("")){
            this.setTitle("首页");
        }else{
            this.setTitle(data);
        }

        setContentView(R.layout.activity_content);

        tvRange = (TextView) findViewById(R.id.range);
        tvPhonetics = (TextView) findViewById(R.id.phonetics);
        tvTranslation = (TextView) findViewById(R.id.translation);
        tvLoading = (LoadingView) findViewById(R.id.loading);

        //发送网页链接请求
        try {
            sendHttpURLConnection(new URL("http://www.iciba.com/" + data));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }


    }



    //连接并解析网页url
    private void sendHttpURLConnection(final URL url) {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedWriter writer = null;
                try{
                    //新建reader
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(TIME_LIMIT);
                    connection.setReadTimeout(TIME_LIMIT);
                    connection.connect();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

                    //读取网页的html文档
                    String string = "";
                    for(String str = reader.readLine() ; str != null ; str = reader.readLine()){
                        string += str + "\n";
                    }

                    //保存html文档
                    if(SAVE_HTML){
                        String fileName;
                        if(data.equals("")){
                            fileName = "首页.html";
                        }else{
                            fileName = data + ".html";
                        }
                        writer = new BufferedWriter(new OutputStreamWriter(openFileOutput(fileName, Context.MODE_PRIVATE)));
                        writer.write(string);
                    }

                    //解析html
                    parseXMLWithPull(string);
                }catch (SocketTimeoutException | UnknownHostException e ){
                    //连接主机超时
                    Message message = new Message();
                    message.what = TIMEOUT;
                    handler.sendMessage(message);
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    //关闭连接
                    if(connection != null){
                        connection.disconnect();
                    }
                    if(writer != null){
                        try {
                            writer.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        };
        //开辟新线程
        new Thread(runnable).start();

    }


    //解析xml
    private void parseXMLWithPull(String xmlData) {
        String range = "";              //存放单词出现范围
        String phonetics = "";          //存放音标
        String translation = "";        //存放翻译
        try {
            //实例化一个新解析器
            XmlPullParser xmlPullParser = XmlPullParserFactory.newInstance().newPullParser();
            xmlPullParser.setInput(new StringReader(xmlData));

            //临时存放字符串
            String str;
            //依次遍历节点
            int eventType = xmlPullParser.getEventType() ;
            while(eventType != XmlPullParser.END_DOCUMENT ){

                String nodeName = xmlPullParser.getName();
                switch (eventType){
                    //起始标签
                    case XmlPullParser.START_TAG:{
                        if(nodeName.equals("td")){
                            str = xmlPullParser.nextText().replaceAll("                                ","    ");
//                            Log.d("TB",str);
                            translation += str;
                        }
                        break;

                    }
                    //结束标签
                    case XmlPullParser.END_TAG:{
                        if(nodeName.equals("tr")){
                            str = "\n";
//                            Log.d("TB",str);
                            translation += str;
                        }
                        break;
                    }
                    //文本
                    case XmlPullParser.TEXT:{
                        str = xmlPullParser.getText();
                        if(str != null){
                            if(str.equals("考研")) {
//                                Log.d("TB", str);
                                range += "考研/";
                            }
                            else if(str.equals("CET6")) {
//                                Log.d("TB", str);
                                range += "CET6/";
                            }
                            else if(str.equals("CET4")) {
//                                Log.d("TB", str);
                                range += "CET4";
                            }
                            else if(str.startsWith("英")) {
//                                Log.d("TB", str);
                                phonetics += str + "    ";
                            }
                            else if(str.startsWith("美")) {
//                                Log.d("TB", str);
                                phonetics += str + "    ";
                            }
                        }
                        break;
                    }

                    default:break;
                }
                try{
                    //下一标签
                    eventType = xmlPullParser.next();
                }catch (XmlPullParserException e){
//                    e.printStackTrace();
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        //发送数据给线程处理
        Message message = new Message();
        message.what = RANGE;
        message.obj = range;
        handler.sendMessage(message);

        Message message2 = new Message();
        message2.what = PHONETICS;
        message2.obj = phonetics;
        handler.sendMessage(message2);

        Message message3 = new Message();
        message3.what = TRANSLATION;
        message3.obj = translation;
        handler.sendMessage(message3);

    }
}
